package utils

import (
	"crypto/md5"
	"fmt"
	"io"
	"mime/multipart"
	"strings"
)

const (
	typeFile = iota
	typeImg
	typeVideo
	typeAudio
)

func HashFile(file *multipart.FileHeader) (hash string, err error) {
	openFile, err := file.Open()
	if err != nil {
		return
	}
	defer openFile.Close()

	h := md5.New()
	_, err = io.Copy(h, openFile)
	if err != nil {
		return
	}
	hash = fmt.Sprintf("%x", h.Sum(nil))
	return
}

func GetFileType(t string) (tp int) {
	t = strings.TrimSpace(strings.ToLower(t)) // 清除空格并转换为小写
	switch t {
	case "image":
		tp = typeImg
		return
	case "video":
		tp = typeVideo
		return
	case "audio":
		tp = typeAudio
		return
	}
	return
}

var typeExtList = map[int][]string{
	typeImg:   {"jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "svg"},
	typeVideo: {"mp4", "avi", "rmvb", "rm", "asf", "divx", "mpg", "mpeg", "mpe", "wmv", "mkv", "vob"},
	typeAudio: {"mp3", "wma", "wav", "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg", "m4a"},
}

func CompareFileTypeExt(tp int, ext string) bool {
	ext = strings.ToLower(ext)
	// remove .
	if len(ext) > 0 && ext[0] == '.' {
		ext = ext[1:]
	}
	for _, v := range typeExtList[tp] {
		if v == ext {
			return true
		}
	}
	return tp == typeFile
}
